<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">营业时间设置</text>
    </view>

    <!-- 营业时间设置 -->
    <view class="section">
      <view class="section-header">
        <text class="section-title">营业时间</text>
        <button class="add-btn" @click="addBusinessHour">添加时段</button>
      </view>
      <view class="business-hour-item" v-for="(hour, index) in shopInfo.businessHoursList" :key="index">
        <view class="time-picker-container">
          <picker mode="time" :value="hour.startTime" @change="(e) => hour.startTime = e.detail.value" start="00:00" end="23:59" class="time-picker">
            <view class="picker">{{hour.startTime || '开始时间'}}</view>
          </picker>
          <text class="time-separator">至</text>
          <picker mode="time" :value="hour.endTime" @change="(e) => hour.endTime = e.detail.value" start="00:00" end="23:59" class="time-picker">
            <view class="picker">{{hour.endTime || '结束时间'}}</view>
          </picker>
        </view>
        <view class="weekday-selector">
          <text>营业日：</text>
          <checkbox-group @change="(e) => updateWeekdays(index, e.detail.value)">
            <label v-for="(day, i) in ['周一','周二','周三','周四','周五','周六','周日']" :key="i">
              <checkbox :value="i" :checked="hour.weekdays[i] === '1'"/>{{day}}
            </label>
          </checkbox-group>
        </view>
        <button class="remove-btn" @click="removeBusinessHour(index)">删除</button>
      </view>
    </view>
  </view>
  <!-- 底部操作按钮 -->
  <view class="footer-btns">
    <button class="cancel-btn" @click="cancelEdit">取消</button>
    <button class="save-btn" @click="saveBusinessHours">保存</button>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/store/user';
import { getMerchantInfo } from '@/api/merchant';
import { saveBusinessHoursList } from '@/api/merchant';


const shopInfo = ref({});

// 获取merchantId的工具函数（与edit.vue保持一致）
function getMerchantId() {
  try {
    const store = useUserStore();
    if (store.merchantId) return store.merchantId;
  } catch(e) {}
  return uni.getStorageSync('merchantId') || '';
}

const addBusinessHour = () => {
  shopInfo.value.businessHoursList.push({
    startTime: '06:00',
    endTime: '22:00',
    weekdays: '1111111'
  });
  
  setTimeout(() => {
    uni.createSelectorQuery().selectAll('.business-hour-item').boundingClientRect(rects => {
      if(rects.length > 0) {
        uni.pageScrollTo({
          scrollTop: rects[rects.length - 1].top,
          duration: 300
        });
      }
    }).exec();
  }, 100);
};

const removeBusinessHour = (index) => {
  shopInfo.value.businessHoursList.splice(index, 1);
};

const updateWeekdays = (index, checkedDays) => {
  let weekdays = ['0','0','0','0','0','0','0'];
  checkedDays.forEach(day => {
    weekdays[day] = '1';
  });
  shopInfo.value.businessHoursList[index].weekdays = weekdays.join('');
};

onLoad(async () => {
  // 从商家信息中获取营业时间数据
  const merchantInfo = await getMerchantInfo(getMerchantId());
  shopInfo.value = merchantInfo.data || {};
});

const cancelEdit = () => {
  uni.navigateBack();
};

const saveBusinessHours = async () => {
  const merchantId = getMerchantId();
  if (!merchantId) {
    uni.showToast({ title: '商户ID缺失', icon: 'none' });
    return;
  }
  // 校验营业时间列表
  if (!shopInfo.value.businessHoursList || shopInfo.value.businessHoursList.length === 0) {
    uni.showToast({ title: '请添加至少一个营业时段', icon: 'none' });
    return;
  }
  uni.showLoading({ title: '保存中...' });
  try {
    await saveBusinessHoursList({
      merchantId,
      businessHoursList: shopInfo.value.businessHoursList.map(item => ({
        startTime: item.startTime,
        endTime: item.endTime,
        weekdays: item.weekdays
      }))
    });
    uni.hideLoading();
    uni.showToast({ title: '保存成功', icon: 'success' });
    setTimeout(() => {
      uni.navigateBack();
    }, 800);
  } catch (e) {
    uni.hideLoading();
    uni.showToast({ title: '保存失败', icon: 'none' });
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
}

.header {
  padding: 30rpx 0;
  text-align: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.section {
  margin: 20rpx 0;
  padding: 20rpx;
  background: #fff;
  border-radius: 10rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.business-hour-item {
  width: 100%;
  margin-bottom: 50rpx;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.time-picker-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 30rpx;
}

.time-separator {
  margin: 0 20rpx;
  font-size: 28rpx;
  color: #999;
}

.picker {
  padding: 10rpx;
  text-align: center;
  font-size: 32rpx;
}

.time-picker {
  width: 100%;
  display: flex;
  justify-content: center;
}

.weekday-selector {
  display: flex;
  align-items: center;
  width: 100%;
  flex-wrap: wrap;
  font-size: 30rpx;
}

.weekday-selector label {
  margin-right: 20rpx;
  font-size: 30rpx;
}

.add-btn {
  background-color: #07C160;
  color: white;
  border-radius: 10rpx;
  transition: transform 0.2s;
}

.add-btn:active {
  transform: scale(0.95);
}

.remove-btn {
  margin-top: 20rpx;
  color: red;
  border-radius: 10rpx;
  padding: 0 20rpx;
  transition: opacity 0.3s;
  width: 33%;
  display: block;
  height: 60rpx;
  line-height: 60rpx;
}
.footer-btns {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0 40rpx 0;
  box-shadow: 0 -2rpx 8rpx rgba(0,0,0,0.04);
  z-index: 99;
}
.cancel-btn {
  background: #f5f5f5;
  color: #333;
  border-radius: 10rpx;
  width: 40%;
  height: 70rpx;
  font-size: 32rpx;
}
.save-btn {
  background: #07C160;
  color: #fff;
  border-radius: 10rpx;
  width: 40%;
  height: 70rpx;
  font-size: 32rpx;
}
</style>